/**
 * @author YangTao
 * @date 2025/4/18
 */
package com.tian.source.controller;

import com.aliyuncs.exceptions.ClientException;
import com.tian.core.beans.ResultBean;
import com.tian.core.exceptions.CheckException;
import com.tian.core.page.Page;
import com.tian.core.utils.MailUtil;
import com.tian.core.utils.SendMessageUtil;
import com.tian.source.model.Notice;
import com.tian.source.model.vo.MailVo;
import com.tian.source.model.vo.MsgVo;
import com.tian.source.model.vo.NoticeVo;
import com.tian.source.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/notice")
public class NoticeController {

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private NoticeService noticeService;
    @Autowired
    private MailUtil mailUtil;

    /**
     * 添加公告
     * @param notice
     * @return
     */
    @PostMapping("/addNotice")
    public ResultBean<String> addNotice(Notice notice){
        notice.setCreateTime(new Date());
        noticeService.add(notice);
        return new ResultBean<>("添加成功");
    }

    /**
     * 分页查询公告
     * @param pageNum
     * @param pageSize
     * @param createTime
     * @param activeTime
     * @return
     */
    @GetMapping("/getAllByPage")
    public ResultBean<Page<List<NoticeVo>>> getAllByPage(Integer pageNum,Integer pageSize,String createTime,String activeTime){
       Page page = new Page(pageNum,pageSize);
       return new ResultBean<>(noticeService.findAllByPage(page,createTime,activeTime));
    }

    @GetMapping("/getNoticeInfoById")
    public ResultBean<NoticeVo> getNoticeInfoById(Integer id){
        return new ResultBean<>(noticeService.findInfoById(id));
    }

    /**
     * 修改公告
     * @param notice
     * @return
     */
    @PostMapping("/updateNotice")
    public ResultBean updateNotice(Notice notice){
        noticeService.modifyById(notice);
        return new ResultBean();
    }

    @PostMapping("/sendMail")
    public ResultBean<String> sendMail(MailVo mailVo){
        mailUtil.sendSimpleEmail(from,mailVo.getTo(),mailVo.getTitle(),mailVo.getContent());
        return new ResultBean<>("发送成功");
    }

    @PostMapping("/sendMsg")
    public ResultBean<String> sendMsg(MsgVo msgVo){
        try {
            SendMessageUtil.sendMessage(msgVo.getPhone(),msgVo.getContent());
        } catch (ClientException e) {
            throw new CheckException("短信发送失败");
        }
        return new ResultBean<>("发送成功");
    }
}
